package org.robot.scm.utils;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.Objects;
import lombok.extern.slf4j.Slf4j;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.json.JSONObject;

@Slf4j
public class BaiduSpeakUtil {

    public static final String API_KEY = "1qO6qyOZYxDSFixM1o94GRHH";
    public static final String SECRET_KEY = "wBYHfBu00iE2DjDhywFE1OQacWHfaMXL";

    static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();

    public static void main(String[] args) {
        speak("现在时间是16:58, 您的血糖值为: 6.8 摩尔每升");
    }

    public static void speak(String text) {
        try {
            MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
            RequestBody body = RequestBody.create("tex=" + URLEncoder.encode(text, "UTF-8") + "&tok=" + getAccessToken() + "&cuid=UttgXEDUwtPwJIkWbhMNdyilu7tqnSOK&ctp=1&lan=zh&spd=4&pit=3&vol=15&per=3&aue=6", mediaType);
            Request request = new Request.Builder()
                    .url("https://tsn.baidu.com/text2audio")
                    .method("POST", body)
                    .addHeader("Content-Type", "application/x-www-form-urlencoded")
                    .addHeader("Accept", "*/*")
                    .build();
            Response response = HTTP_CLIENT.newCall(request).execute();
            AudioSoundUtil.playSound(Objects.requireNonNull(response.body()).byteStream());
        } catch (Exception e) {
            log.error("baidu speak utils error", e);
        }
    }

    /**
     * 从用户的AK，SK生成鉴权签名（Access Token）
     *
     * @return 鉴权签名（Access Token）
     * @throws IOException IO异常
     */
    static String getAccessToken() throws IOException {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create("grant_type=client_credentials&client_id=" + API_KEY + "&client_secret=" + SECRET_KEY, mediaType);
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/oauth/2.0/token")
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        return new JSONObject(Objects.requireNonNull(response.body()).string()).getString("access_token");
    }

}
